import React from 'react'
import {
  Button,
  Modal,
  message,
  Input,
  Select,
  TreeSelect,
  Upload,
  Spin,
  Affix,
  BackTop,
  Row,
  Col,
  Tooltip,
  Switch,
} from 'antd'
import {
  BaseListPage,
  IBaseListPageState,
  uaaApp,
  validators,
  UdPage,
  UdPageHeader,
  udConfigProvider,
  UdFilter,
  UdToolbar,
  UdTable,
  routeUtils,
  IListQueryParams,
} from '../../../lib'
import { columnRenders } from '../../../lib/utils/columnRenders'
import { UdModal, UdModalForm } from '../../../lib/ui/UdModal'
import { http } from '../../../lib/core/http'
import apis from '@/apis/UserManagement'
import { resetPassword, enableHandle } from '../common'
import _ from 'lodash'
import EnableRadioGroup from '../component/EnableRadioGroup'
import comApis from '@/apis'
import './style.scss'
import { downBlobFile } from '@/utils/methods'
import { RouteComponentProps } from 'react-router-dom'
import Form, { WrappedFormUtils } from 'antd/lib/form/Form'
import OrgTree from './component/OrgTree'
import ButtonGroup from 'antd/lib/button/button-group'

const confirm = Modal.confirm
const Option = Select.Option

const EnableBtnAuth = 'user_lzlj_employee_manager_invalid'
const UpdateBtnAuth = 'user_lzlj_employee_manager_add'
const ResetPasswordBtnAuth = 'user_lzlj_employee_manager_rest_password'

// class InternalStaffList extends BasePage<IInternalStaffListProps, IInternalStaffListState> {
class InternalStaffList extends BaseListPage<IInternalStaffListProps, IInternalStaffListState> {
  protected saveParamsWithUrl = true
  /** 滚动条容器 */
  protected pageContainer = udConfigProvider.ui.getPageContainer()
  /** 条件过滤器的表单对象 */
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private statusTranslate = {
    0: '禁用',
    1: '启用',
  }

  private statusOptions = [
    ...Object.keys(this.statusTranslate).map(key => ({ value: key, name: this.statusTranslate[key] })),
  ]

  private modal
  constructor(props) {
    super(props)
    this.state = {
      title: '内部员工账号管理',
      queryApi: params => {
        return http.post(apis.InternalStaffList, params)
      },
      conditions: [
        { id: 'userCode', label: '员工编码' },
        { id: 'realName', label: '员工姓名' },
        {
          id: 'isValid',
          label: '状态',
          render: (
            <Select placeholder="请输入状态">
              {this.statusOptions.map(({ value, name }) => (
                <Option key={value} value={value}>
                  {name}
                </Option>
              ))}
            </Select>
          ),
        },
        { id: 'roleName', label: '角色' },
      ],
      rowKey: 'id',
      columns: [
        ['员工编码', 'userCode', null, { width: '80px' }],
        ['员工姓名', 'realName', null, { width: '80px' }],
        ['员工手机号', 'phone', null, { width: '90px' }],
        {
          dataIndex: 'unSyn',
          title: '限制同步',
          width: 80,
          render: (text, record, index) => {
            return (
              <Switch
                checked={record['unSyn'] === 1}
                onChange={val => {
                  //0否，1是
                  let value = val ? 1 : 0
                  this.handChangeUnSyn(record.id, value, index)
                }}
                checkedChildren="是"
                unCheckedChildren="否"
              ></Switch>
            )
          },
        },
        {
          title: '所属组织',
          dataIndex: 'mechanismName',
          width: 300,
          render: (text, record) => {
            return (
              <Tooltip title={record.mechanismName}>
                <div style={{ width: '300px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.mechanismName}
                </div>
              </Tooltip>
            )
          },
        },
        {
          title: '角色',
          dataIndex: 'roleName',
          width: 300,
          render: (text, record) => {
            return (
              <Tooltip title={record.roleName}>
                <div style={{ width: '300px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.roleName}
                </div>
              </Tooltip>
            )
          },
        },
        {
          title: '职位名称',
          dataIndex: 'postnNames',
          width: 300,
          render: (text, record) => {
            return (
              <Tooltip title={record.postnNames}>
                <div style={{ width: '300px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
                  {record.postnNames}
                </div>
              </Tooltip>
            )
          },
        },
        ['状态', 'isValid', columnRenders.enum(this.statusTranslate), { width: '60px' }],
        ['创建时间', 'createTime', null, { width: '180px' }],
        ['修改时间', 'updateTime', null, { width: '180px' }],
        ['修改人', 'updateBy', null, { width: '100px' }],
        {
          title: '操作',
          dataIndex: 'operate',
          fixedWidth: '100px',
          allowCustomize: false,
          fixed: 'right',
          render: columnRenders.operate([
            {
              title: '编辑',
              auth: UpdateBtnAuth,
              action: (text: any, row: any) => this.edit(row),
            },
            {
              title: '重置密码',
              auth: ResetPasswordBtnAuth,
              action: (text: any, record: any) => {
                // 设置默认的重置密码
                record.password = `Jxsmh@${record.userCode}`
                confirm({
                  title: '确定要重置登录密码吗？',
                  content: (
                    <Form labelCol={{ span: 6 }} wrapperCol={{ span: 12 }}>
                      <Row gutter={24}>
                        <Col>
                          <Form.Item label={'设置密码'} required={true}>
                            <Input
                              onChange={e => {
                                record.password = e.target.value
                              }}
                              defaultValue={`${record.password}`}
                            />
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form>
                  ),
                  onOk: () => {
                    if (!record.password) {
                      message.error('请填写修改的密码')
                      return Promise.reject('请填写修改的密码')
                    }
                    const reg: any = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/
                    if (!reg.test(record.password)) {
                      message.error('密码至少包含大写字母，小写字母，数字，且不少于8位')
                      return Promise.reject('密码至少包含大写字母，小写字母，数字，且不少于8位')
                    }
                    this.resetPassword(record)
                  },
                })
              },
            },
          ]),
        },
      ],
      leftBtns: [
        <Button type="primary" onClick={this.addUser}>
          新增
        </Button>,
        // <Button type='primary' onClick={this.importModal}>导入</Button>,
        uaaApp.canUse(EnableBtnAuth) &&
          (() => (
            <Button type="primary" disabled={!this.existSelectedRow()} onClick={() => this.enableHandle(true)}>
              启用
            </Button>
          )),
        uaaApp.canUse(EnableBtnAuth) &&
          (() => (
            <Button disabled={!this.existSelectedRow()} onClick={() => this.enableHandle(false)}>
              禁用
            </Button>
          )),
      ],
      tableProps: {
        rowSelection: !uaaApp.canUse(EnableBtnAuth) ? null : {},
        scroll: {
          x: true,
        },
      },
      organizationList: [],
      roleList: [],
      uploading: false,
      selectOrgCode: undefined,
    }
  }

  public componentWillMount() {
    super.componentWillMount()
    this.getOrganizationList()
    this.getRoleSelectList()
    const { conditions } = routeUtils.searchStringToObject(this.props.location.search, { conditions: {} })
    this.setState({
      selectOrgCode: conditions?.organizationCode,
    })
  }

  render() {
    const { conditions, leftBtns, columns, selectOrgCode } = this.state
    const defaultSelectedKeys = selectOrgCode ? [selectOrgCode] : undefined
    return (
      <Spin wrapperClassName="full-flex-loading" spinning={this.state.uploading} tip="正在上传，请稍后...">
        <UdPage className="list-page internal-staff-list">
          <UdPageHeader title={this.state.title} affixProps={{ target: () => this.pageContainer }} />
          <div className="internal-staff-bd">
            <div className="org-tree-box">
              <OrgTree onSelect={this.orgTreeOnSelect} defaultSelectedKeys={defaultSelectedKeys} />
            </div>
            <div className="table-list-box">
              {_.isArray(conditions) && conditions.length > 0 && (
                <UdFilter
                  loading={this.state.querying}
                  items={conditions}
                  getForm={form => {
                    this.filterForm = form
                  }}
                  onSearch={this.handleSearch}
                  resetAfter={this.filterReset}
                ></UdFilter>
              )}
              <Affix className="ud-page-toolbar-affix" offsetTop={40} target={() => this.pageContainer}>
                <UdToolbar other={<ButtonGroup>{this.buildToolbarBtns(leftBtns)}</ButtonGroup>}></UdToolbar>
              </Affix>
              <UdTable
                pagination={this.state.pagination}
                loading={this.state.querying}
                rowKey={this.state.rowKey}
                {...this.state.tableProps}
                columns={columns}
                dataSource={this.state.dataSource}
                onChange={this.handleTableChange}
              />
              {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}
            </div>
          </div>
        </UdPage>
      </Spin>
    )
  }

  private handChangeUnSyn = (userId, unSyn, index) => {
    this.setState({ querying: true })
    let { dataSource } = this.state
    dataSource[index]['unSyn'] = unSyn
    http
      .get(apis.wineryUserUnSyn, {
        params: { userId, unSyn },
      })
      .then(() => {
        this.setState({ dataSource }, () => {
          message.success('操作成功')
        })
      })
      .finally(() => {
        this.setState({ querying: false })
      })
  }

  /* 组织树选中后通过改变路由地址触发请求 */
  public orgTreeOnSelect = selectedKeys => {
    let organizationCode = undefined
    if (selectedKeys && selectedKeys.length > 0) {
      organizationCode = selectedKeys[0]
    }
    this.setState(
      {
        selectOrgCode: organizationCode,
      },
      () => {
        if (organizationCode) {
          this.pushQueryParams({ conditions: { organizationCode } }, false)
        } else {
          this.pushQueryParams({}, false)
        }
      }
    )
  }

  /**
   * 处理条件过滤器查询事件
   */
  protected handleSearch = (values: any) => {
    let p: Partial<IListQueryParams> = {
      // 搜索操作需要将已选择的组织条件放到请求参数数据里
      conditions: { ...values, organizationCode: this.state.selectOrgCode },
      v: new Date().getTime(),
    }
    if (this.state.pagination) {
      p.page = 1
    }
    // p.organizationCode = this.state.selectOrgCode
    this.handleParamsChange<IListQueryParams>(p)
  }

  private getOrganizationList = () => {
    http.get(comApis.OrganizationTreeByUser).then(res => {
      const { nodes } = this.frormatTreeData([res.data])
      this.setState({
        organizationList: nodes,
      })
    })
  }

  private getRoleSelectList = () => {
    const params = { roleType: 0 }
    http.get(apis.RoleSelectList, { params }).then(res => {
      const roleList = res.data.map(({ id, name }) => ({ value: id, name }))
      this.setState({
        roleList,
      })
    })
  }

  private frormatTreeData = datas => {
    let nodes: any = []
    const loopFormat = datas => {
      if (!_.isArray(datas) || datas.length == 0) {
        return []
      }
      let treeNodes = []
      datas.map(item => {
        const { children, name: title, id: key, id: value } = item
        let treeNode = { key, value, title, children }
        treeNode.children = loopFormat(children)
        treeNodes.push(treeNode)
      })
      return treeNodes
    }
    nodes = loopFormat(datas)
    return { nodes }
  }

  private importModal = () => {
    this.modal = UdModal.open({
      title: '导入员工',
      width: 300,
      content: (
        <>
          <div className="import-user-modal">
            <Button type="primary" onClick={this.downloadTpl}>
              下载模板
            </Button>
            <Upload showUploadList={false} customRequest={this.importUser}>
              <Button type="primary">导入员工</Button>
            </Upload>
          </div>
        </>
      ),
      footer: null,
      maskClosable: false,
      centered: true,
    })
  }

  private importUser = option => {
    this.modal && this.modal.destroy()
    this.setState({ uploading: true })
    const { file } = option
    const formData = new FormData()
    formData.append('file', file)
    http
      .post(apis.ImportInternalStaff, formData)
      .then(res => {
        message.success('上传成功')
        this.query()
      })
      .finally(() => this.setState({ uploading: false }))
  }

  private downloadTpl = () => {
    http.get(apis.DownloadInternalStaffTpl, { responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, '内部员工导入模板')
      }
    })
  }

  private addUser = () => {
    const initValue = {
      isValid: 1,
    }
    const { organizationList, roleList } = this.state
    UdModal.open({
      title: '新增',
      width: '40%',
      content: (
        <UdModalForm
          items={[
            {
              id: 'userCode',
              label: '员工编码',
              rules: [validators.required, validators.max(10), validators.userCode],
            },
            {
              id: 'realName',
              label: '员工姓名',
              rules: [validators.required, validators.max(10), validators.userName],
            },
            {
              id: 'phone',
              label: '员工手机号',
              rules: [validators.required, validators.phoneCommonly],
              decoratorOptions: { validateFirst: true },
            },
            {
              id: 'orgCode',
              label: '所属组织',
              render: (
                <TreeSelect
                  multiple
                  treeNodeFilterProp="title"
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  showSearch={true}
                  treeData={organizationList}
                />
              ),
            },
            {
              id: 'roleId',
              label: '角色',
              render: () => (
                <Select
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  mode="multiple"
                  optionFilterProp="children"
                >
                  {roleList.map(({ value, name }) => (
                    <Option key={value} value={value}>
                      {name}
                    </Option>
                  ))}
                </Select>
              ),
            },
            { id: 'isValid', label: '状态', render: <RadioCm /> },
          ]}
          values={initValue}
        />
      ),
      onOk: values => {
        values.orgCode = values?.orgCode?.join(',')
        return http.post(apis.AddInternalStaff, values).then(res => {
          message.success('新增成功')
          this.query()
        })
      },
    })
  }

  private edit = row => {
    const { organizationList, roleList } = this.state
    if (!Array.isArray(row.roleId)) {
      row.roleId = row.roleId?.split(',')
    }
    if (!Array.isArray(row.depmentIds)) {
      row.depmentIds = row.depmentIds?.split(',')
    }
    UdModal.open({
      title: '编辑',
      width: '40%',
      content: (
        <UdModalForm
          items={[
            { id: 'userCode', label: '员工编码', render: <Input disabled /> },
            { id: 'realName', label: '员工姓名', render: <Input disabled /> },
            { id: 'phone', label: '员工手机号', render: <Input disabled /> },
            /* { id: 'depmentId', label: '所属组织', render: 
          <Select>
            <Option value='1'>泸州老窖</Option>
          </Select>
        }, */
            {
              id: 'depmentIds',
              label: '所属组织',
              render: (
                <TreeSelect
                  multiple
                  treeNodeFilterProp="title"
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  showSearch={true}
                  treeData={organizationList}
                />
              ),
            },
            {
              id: 'roleId',
              label: '角色',
              render: () => (
                <Select
                  getPopupContainer={triggerNode => triggerNode.parentElement}
                  mode="multiple"
                  optionFilterProp="children"
                >
                  {roleList.map(({ value, name }) => (
                    <Option key={value} value={value}>
                      {name}
                    </Option>
                  ))}
                </Select>
              ),
            },
            { id: 'isValid', label: '状态', render: <RadioCm /> },
          ]}
          values={row}
        />
      ),
      onOk: values => {
        values.id = row.id
        // 修改需要给旧的组织id
        values.oldDepmentIds = row?.depmentIds?.join(',')
        if (Array.isArray(values.depmentIds)) {
          values.depmentIds = values.depmentIds?.join(',')
        }
        console.log('values :>> ', values)
        return http.post(apis.UpdateInternalStaff, values).then(res => {
          message.success('编辑成功')
          this.query()
        })
      },
    })
  }

  private resetPassword = row => {
    const { id, password } = row
    return resetPassword({
      url: apis.ResetPasswordInternalStaff,
      params: { id, password },
    })
  }

  private enableHandle = flag => {
    const idList = this.state.selectedRowKeys?.join(',')
    const isValid = flag ? 1 : 0
    enableHandle({
      flag,
      url: apis.EnableInternalStaff,
      params: {
        idList,
        isValid,
      },
      cb: () => {
        this.query()
      },
    })
  }
}

export default InternalStaffList

interface IInternalStaffListProps extends RouteComponentProps {}

interface IInternalStaffListState extends IBaseListPageState {
  organizationList: any
  roleList: any
  uploading?: boolean
  selectOrgCode?: string
}

function RadioCm(props) {
  return <EnableRadioGroup onChange={props.onChange} value={props.value} />
}
